﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Net.Http;
using System.Threading;

namespace NFinal.Middleware.Proxy
{
    public class OwinProxyMiddleware: ProxyMiddleware<IDictionary<string,object>>
    {
        public OwinProxyMiddleware(InvokeDelegate<IDictionary<string, object>> next, ProxyConfig config):base(next,config)
        {
        }
        public override string GetRequestPath(IDictionary<string, object> context)
        {
            return (string)context["owin.RequestPath"];
        }
        public override string GetRequestQueryString(IDictionary<string, object> context)
        {
            return (string)context["owin.RequestQueryString"];
        }
        public override string GetRequestMethod(IDictionary<string, object> context)
        {
            return (string)context["owin.RequestMethod"];
        }
        public override Stream GetRequestBody(IDictionary<string, object> context)
        {
            return (Stream)context["owin.RequestBody"];
        }
        public override void AddOrUpdateResponseHeader(IDictionary<string, object> context, string key, string[] value)
        {
            IDictionary<string, string[]> headers = (IDictionary<string, string[]>)context["owin.ResponseHeaders"];
            if (headers.ContainsKey(key))
            {
                headers[key] = value;
            }
            else
            {
                headers.Add(key,value);
            }
        }
        public override void AddRequestHeadersToHttpRequestMessage(IDictionary<string, object> context, HttpRequestMessage message)
        {
            IDictionary<string, string[]> headers = (IDictionary<string, string[]>)context["owin.RequestHeaders"];
            foreach (var header in headers)
            {
                AddRequestHeaderToHttpRequestMessage(context, message, header.Key, header.Value);
            }
        }
        public override CancellationToken GetCancellationToken(IDictionary<string, object> context)
        {
            return (CancellationToken)context["owin.CallCancelled"];
        }
        public override Stream GetResponseBody(IDictionary<string, object> context)
        {
            return (Stream)context["owin.ResponseBody"];
        }
        public override void RemoveResponseHeader(IDictionary<string, object> context, string key)
        {
            IDictionary<string, string[]> headers = (IDictionary<string,string[]>)context["owin.ResponseHeaders"];
            headers.Remove(key);
        }
        public override void SetResponseStatusCode(IDictionary<string, object> context, int statusCode)
        {
            context["owin.ResponseStatusCode"] = statusCode;
        }
    }
}
